<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>继承的应用-拖拽</title>
	<style>
		#div1 {
			width: 200px;
			height: 200px;
			background-color: crimson;
			position: absolute
		}

		#div2 {
			width: 200px;
			height: 200px;
			background-color: dodgerblue;
			position: absolute;
			left: 220px;
		}
	</style>
</head>
<body>
<div id="div1">1111</div>
<div id="div2">2222</div>

<script>
	/*面向过程写法*/
	/*window.onload = function (){
	 var oDiv1 = document.getElementById("div1");
	 //			console.log(oDiv1);
	 var disX = 0;
	 var disY = 0;
	 oDiv1.onmousedown = function(ev){
	 var ev = ev || window.event;
	 //鼠标在元素上按下的时候 disX/Y =（下鼠标的x和y坐标）- （记录下元素的x和y坐标 ）

	 disX = ev.clientX - oDiv1.offsetLeft;
	 disY = ev.clientY - oDiv1.offsetTop;
	 //				console.log(disX+"---"+disY);

	 document.onmousemove = function(ev){
	 var ev = ev || window.event;
	 oDiv1.style.left = ev.clientX - disX + 'px';
	 oDiv1.style.top = ev.clientY - disY + 'px';
	 };

	 document.onmouseup = function(){
	 document.onmousemove = null;
	 document.onmouseup = null;
	 }
	 };
	 }*/

	/*面向对象写法*/

	window.onload = function () {
		var d1 = new Drag("div1");
		d1.inicial();
		var d2 = new subDrag("div2");
		d2.inicial();
	};
	/*
	 * 定义父类
	 * */
	function Drag(id) {
		this.obj = document.getElementById(id);
		this.disX = 0;
		this.disY = 0;
	}
	Drag.prototype.inicial = function () {
		var This = this;

		this.obj.onmousedown = function (ev) {
			var ev = ev || window.event;
			This.fnDown(ev);

			document.onmousemove = function (ev) {
				var ev = ev || window.event;
				This.fnMove(ev);
			};

			document.onmouseup = function () {
				This.fnUp();
			};
			return false;
		};
	};

	Drag.prototype.fnDown = function (ev) {
		this.disX = ev.clientX - this.obj.offsetLeft;
		this.disY = ev.clientY - this.obj.offsetTop;
	};
	Drag.prototype.fnMove = function (ev) {
		this.obj.style.left = ev.clientX - this.disX + 'px';
		this.obj.style.top = ev.clientY - this.disY + 'px';
	};
	Drag.prototype.fnUp = function () {
		document.onmousemove = null;
		document.onmouseup = null;
	};
	/*
	 * 子类继承父类
	 * */
	function subDrag(id) {
		Drag.call(this, id);
	}
	/*通过复制继承，来继承Drag的方法*/
	extend(subDrag.prototype, Drag.prototype);

	subDrag.prototype.fnMove = function (ev) {
		var x = ev.clientX - this.disX;
		var y = ev.clientY - this.disY;

		if (x < 0) {
			x = 0;
		} else if (x > document.documentElement.clientWidth - this.obj.offsetWidth) {
			x = document.documentElement.clientWidth - this.obj.offsetWidth
		}

		this.obj.style.left = x + 'px';
		this.obj.style.top = y + 'px';
	};

	/*
	 * 复制继承函数
	 * */
	function extend(obj1, obj2) {
		for (var attr in obj2) {
			obj1[attr] = obj2[attr];
		}
	}
</script>
</body>
</html>